package com.xiaoma.verbal.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.xiaoma.verbal.baseDao.BaseDaoImpl;
import com.xiaoma.verbal.baseDao.DefaultRowMapper;
import com.xiaoma.tpo.domain.ChChapter;
import com.xiaoma.verbal.domain.FctForecast;
import com.xiaoma.verbal.domain.FctQuestion;
import com.xiaoma.verbal.domain.QuQuestion;
import com.xiaoma.verbal.dto.FctQuestionVo;
import com.xiaoma.verbal.dto.QuestionVo;
import com.xiaoma.verbal.dto.QuestionVo;

@Repository
public class FctQuestionDao extends BaseDaoImpl<FctQuestion> {
	private static final Logger LOG = LoggerFactory.getLogger(FctQuestionDao.class);

	@SuppressWarnings("unchecked")
	public List<FctQuestion> findByFctId(Integer fctId) {
		String sql = "SELECT * FROM fct_question f where f.forecast_id = ? ";
		LOG.info("SQL:{} PARAMS:{}", sql, fctId);
		List<?> result = jdbcTemplate.query(sql, new DefaultRowMapper(FctQuestion.class, getNameHandler()), fctId);
		return (List<FctQuestion>) result;
	}

	@SuppressWarnings("unchecked")
	public List<QuestionVo> findFQubyId(Integer fctId) {
		String sql = "SELECT b.*,a.uuid FROM fct_question a left join qu_question b on a.question_id = b.id where a.forecast_id = ? ";
		LOG.info("SQL:{} PARAMS:{}", sql, fctId);
		List<?> result = jdbcTemplate.query(sql, new DefaultRowMapper(QuestionVo.class, getNameHandler()), fctId);
		return (List<QuestionVo>) result;
	}

	public Map<String, Object> getTop3Coordinate(Integer[] forecastIds) {
		String sql = "SELECT count(b.id) total,sum(b.update_time) sumTime FROM fct_question a left join qu_question b on a.question_id = b.id ";

		if (forecastIds != null) {
			String condition = " where 1=1 ";
			for (Integer id : forecastIds) {
				condition = condition + " or a.forecast_id =" + id;
			}
			sql = sql + condition;
		}

		Map<String, Object> result = jdbcTemplate.queryForObject(sql, new RowMapper() {

			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				// TODO Auto-generated method stub
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("total", rs.getInt("total"));
				map.put("sumTime", rs.getLong("sumTime"));
				return map;
			}

		});
		return result;
	}

	public int deleteByForecastId(Integer id) {
		// TODO Auto-generated method stub
		String sql = "DELETE  FROM fct_question  where forecast_id = ? ";
		LOG.info("SQL:{} PARAMS:{}", sql, id);
		return jdbcTemplate.update(sql,id);
	}

}
